#!/bin/bash

# 监听指定的进程信息
# ./top.sh 进程名1 [进程名2...] > log

# 输出文件名
log="${0%.*}.$(date "+%Y-%m-%d_%H-%M-%S").log"

# 进程列表
sliProc=$@

# 调用间隔
interval=3

# 获取进程PID
retGetPID=0
function getPID()
{
	local proc=$1
	retGetPID=`ps aux | grep -w $proc | grep -v grep | grep -v $0 | awk '{print $2}'`
}

# 获取所有进程PID列表,已','分隔
retGetAllPID=""
function getAllPID()
{
	retGetAllPID=""
	for proc in $sliProc; do
		getPID $proc
		if [ -z "$retGetAllPID" ]; then
			retGetAllPID=$retGetPID
		else
			if [ ! -z $retGetPID ]; then
				retGetAllPID=$retGetPID","$retGetAllPID
			fi
		fi
	done
}

# 输出系统资源占用
function logTopInfo()
{
	`top -H -b -n 1 -p $retGetAllPID >> $log`
}

# 获取所有监视的pid列表
getAllPID

# 输出监听的进程PID
echo "PID:$retGetAllPID" >> $log
echo "" >> $log

# 主循环
while [ 1 ]; do
	sleep $interval
	echo $(date "+%Y-%m-%d %H:%M:%S") >> $log
	echo " " >> $log
	logTopInfo
	echo "=====================================" >> $log
	echo "" >> $log
done

